package com.sigmazero13.MKDummy.listeners;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;

public class DummyPlayerTabListener<T extends Fragment & OnTabUnselectedListener> implements ActionBar.TabListener {

	private T fragment;
	private boolean wasAdded = false;
	private final Activity activity;
	private String tag;
	private Class<T> mClass;
	
	public DummyPlayerTabListener(Activity activity, String tag, Class<T> clazz) {
		this.activity = activity;
		this.tag = tag;
		mClass = clazz;
	}
	
	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		if (!wasAdded) {
			ft.add(android.R.id.content, getFragment(), tag);
			wasAdded = true;
		} else {
			ft.attach(fragment);
		}
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		if (fragment != null) {
			fragment.onTabUnselected();
			ft.detach(fragment);
		}
	}
	
	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// nothing
	}
	
	@SuppressWarnings("unchecked")
	public T getFragment() {
		if (fragment == null) {
			fragment = (T)Fragment.instantiate(activity, mClass.getName());
		}
		return fragment;
	}

}
